package cn.krui.project.controller.system;

import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.jdbc.ScriptRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import cn.krui.helper.bean.AppResult;
import cn.krui.helper.db.DBHelper; 
import cn.krui.helper.tools.MapUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @author zc
 */
@RestController
@RequestMapping(value = "/system/system_check")
@Api(tags = "运维-版本及初始化", description = "数据无价 谨慎操作", hidden = true)
@CrossOrigin
public class SystemCheckController extends SystemBaseController{

	@Autowired
    private DBHelper dbHelper; 

    /**
     * 系统部门
     */
    private Integer qrSysDept = 1;
    /**
     * 系统登录日志
     */
    private Integer qrSysLoginLogs = 1;
    /**
     * 系统菜单
     */
    private Integer qrSysMenu = 1;
    /**
     * 系统参数
     */
    private Integer qrSysParams = 1;
    /**
     * 系统权限
     */
    private Integer qrSysPermissions = 1;
    /**
     * 系统角色
     */
    private Integer qrSysRole = 1;
    /**
     * 系统标签
     */
    private Integer qrSysTags = 1;
    /**
     * 系统用户
     */
    private Integer qrSysUsers = 1;

    private final String COM_QR_WEB_COMMON_DEBUG = "com.qr.web.common.debug";
    private final String EQUALS_COM_QR_WEB_COMMON_DEBUG = "1";
    private final String EQUALS_CNT = "cnt";
    private final String EQUALS_QRSYSDEPT = "qr_sys_dept";
    private final String EQUALS_QRSYSLOGINLOGS = "qr_sys_login_logs";
    private final String EQUALS_QRSYSMENU = "qr_sys_menu";
    private final String EQUALS_QRSYSPARAMS = "qr_sys_Params";
    private final String EQUALS_QRSYSPERMISSIONS = "qr_sys_permissions";
    private final String EQUALS_QRSYSROLE = "qr_sys_role";
    private final String EQUALS_QRSYSTAGS = "qr_sys_tags";
    private final String EQUALS_QRSYSUSERS = "qr_sys_users";
    
    @GetMapping(value = "/checkVersion")
	@ApiOperation(value = "版本检查", httpMethod = "GET")
    public AppResult<String> checkVersion(){
        AppResult<String> app = new AppResult<String>();
        if(!env.getProperty(COM_QR_WEB_COMMON_DEBUG).equals(EQUALS_COM_QR_WEB_COMMON_DEBUG)){
            app.setMsg("无权访问");return app;
        }
        Map<String,Object> cknum = dbHelper.selectOne("COUNT(1) cnt", "information_schema.`TABLES`", "TABLE_SCHEMA = DATABASE() AND TABLE_NAME='qr_version'", null);
        if(MapUtils.getInt(cknum, EQUALS_CNT)==0){
            app.setMsg("版本表缺失！");
            return app;
        }
        List<Map<String,Object>> ckqv = dbHelper.select("qv.tb_name,qv.version_id", "qr_version qv", "", null);
        Map<String,Integer> ckqvmap = new HashMap<>(10);
        for (Map<String,Object> map : ckqv) {
            ckqvmap.put(MapUtils.getString(map, "tb_name"),MapUtils.getInt(map, "version_id"));
        }
        if (ckqvmap.get(EQUALS_QRSYSDEPT) != qrSysDept) {
            app.setMsg("系统部门表版本不对");
        }
        if (ckqvmap.get(EQUALS_QRSYSLOGINLOGS) != qrSysLoginLogs) {
            app.setMsg("系统登录日志表版本不对");
        }
        if (ckqvmap.get(EQUALS_QRSYSMENU) != qrSysMenu) {
            app.setMsg("系统菜单表版本不对");
        }
        if (ckqvmap.get(EQUALS_QRSYSPARAMS) != qrSysParams) {
            app.setMsg("系统参数表版本不对");
        }
        if (ckqvmap.get(EQUALS_QRSYSPERMISSIONS) != qrSysPermissions) {
            app.setMsg("系统权限表版本不对");
        }
        if (ckqvmap.get(EQUALS_QRSYSROLE) != qrSysRole) {
            app.setMsg("系统角色表版本不对");
        }
        if (ckqvmap.get(EQUALS_QRSYSTAGS) != qrSysTags) {
            app.setMsg("系统标签表版本不对");
        }
        if (ckqvmap.get(EQUALS_QRSYSUSERS) != qrSysUsers) {
            app.setMsg("系统用户版本不对");
        }
        if (!StringUtils.isEmpty(app.getMsg())) {
            return app;
        }
        app.ok("没发现问题，请谨慎操作数据库");
        return app;
    }

    
    @GetMapping(value = "/initDB")
	@ApiOperation(value = "数据库初始化", httpMethod = "GET")
    public AppResult<String> initdb(){
        AppResult<String> app = new AppResult<String>();
        if(!env.getProperty(COM_QR_WEB_COMMON_DEBUG).equals(EQUALS_COM_QR_WEB_COMMON_DEBUG)){
            app.setMsg("无权访问");return app;
        }
        Map<String,Object> cknum = dbHelper.selectOne("COUNT(1) cnt", "information_schema.`TABLES`", "TABLE_SCHEMA = DATABASE() AND TABLE_NAME='qr_version'", null);
        if(MapUtils.getInt(cknum, EQUALS_CNT)>0){
            app.setMsg("只有新建的数据库才能初始化！");
            return app;
        }
        try { 
            String url = env.getProperty("spring.datasource.url");
            String driver = env.getProperty("spring.datasource.driverClassName");
            String username = env.getProperty("spring.datasource.username");
            String password = env.getProperty("spring.datasource.password");

            Class.forName(driver).newInstance();
            Connection conn =DriverManager.getConnection(url, username, password);
            ScriptRunner runner = new ScriptRunner(conn); 
            /**
             * 自动提交
             */
            runner.setAutoCommit(true);
            runner.setFullLineDelimiter(false);
            /**
             * 每条命令间的分隔符
             */
			runner.setDelimiter(";");
			runner.setSendFullScript(false);
			runner.setStopOnError(false); 
            String path = this.getClass().getClassLoader().getResource("crebas.sql").getPath();
            System.out.println(path); 
            runner.runScript(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("crebas.sql")));
            runner.closeConnection();
            conn.close();

        } catch (Exception e) {
            e.printStackTrace();
        } 
        app.ok("执行成功");
        return app;
    }
}